#!/bin/sh

LOG="logger -t genkey"

start() {
    if [ ! -f /etc/miniupnpd.conf.uuid ] && [ -f /bin/miniupnpd ]; then
       $LOG "No UPNP UUID found. Generate new UUID."
       num=0
        for i in `seq 1 36`; do
            id=`cat /dev/urandom | hexdump | head -1 | cut -c9`
            num=`expr $num + 1`
            if [ "$num" = "9" ] || [ "$num" = "19" ] || [ "$num" = "24" ]; then
	        id="-"
            fi
            outid="$outid$id"
        done
        serial=`echo "$outid" | cut -f1 -d-`
        $LOG "UPNP UUID is $outid , serial is $serial"
	printf "uuid=$outid\nserial=$serial\n" > /etc/miniupnpd.conf.uuid
    fi

    if [ ! -f /etc/dropbear/dropbear_dss_host_key ] && [ -f /bin/dropbear ]; then
	$LOG "No DSS key found. Generate new host key."
	mkdir -p /etc/dropbear
	if [ -f /tmp/is_16ram_dev ]; then
	    # this is workaround for small memory devices
	    # move update firmware at 2 sateges mode
	    # 1. generate new host key and reboot
	    # 2. normal boot
    	    dropbearkey -t dss -f /etc/dropbear/dropbear_dss_host_key && fs backup_nvram && fs save && sleep 3 && reboot
	else
    	    (dropbearkey -t dss -f /etc/dropbear/dropbear_dss_host_key) &
	fi
    fi

}

stop() {
    :
}

case "$1" in
	start)
	    start
	    ;;

	stop)
	    stop
	    ;;

	restart)
	    stop
	    start
	    ;;

	*)
	    echo $"Usage: $0 {start|stop|restart}"
	    exit 1
esac
